{extend name="layout/iframe_layout" /}

{block name="title"}一键curd{/block}
{block name="style"}
<style>
.crud-generator {
  padding: 20px;
}

.columns-config {
  margin: 20px 0;
}

.option-item {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}
</style>
{/block}

{block name="content"}

<div id="app" >
    <div class="crud-generator">
    <el-form :model="config" label-width="150px">
      <!-- 表名输入 -->
      <el-form-item label="表名" required>
        <el-input
          v-model="config.tableName"
          placeholder="请输入表名包含前缀，如:bs_order"
          style="width: 300px"
        ></el-input>
        <el-button style="margin-left: 20px" size="medium" type="primary"
                   @click="handleTableNameChange(config.tableName)"
                   :loading="isLoading"
        >查询
        </el-button>
        <!--创建新表-->
        <el-button style="margin-left: 20px" size="medium" type="warning"
                   @click="handleCreateTable()"
                   :loading="isLoading"
        >创建表
        </el-button>
      </el-form-item>
      <el-form-item label="后台接口配置" v-if="columns.length">
        <el-checkbox-group v-model="admin_apis">
          <el-checkbox label="save_data">新增</el-checkbox>
          <el-checkbox label="edit_data">修改</el-checkbox>
          <el-checkbox label="del_data">删除</el-checkbox>
          <el-checkbox label="list">数据列表</el-checkbox>
          <el-checkbox label="get">查看详情</el-checkbox>
          <el-checkbox label="list_options">下拉选项</el-checkbox>
          <el-checkbox label="status">快速修改状态</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="前端接口配置" v-if="columns.length">
        <el-checkbox-group v-model="apis">
          <el-checkbox label="list">数据列表</el-checkbox>
          <el-checkbox label="detail">数据详情</el-checkbox>
          <el-checkbox label="action">增改操作</el-checkbox>
          <el-checkbox label="setDefault">设为默认</el-checkbox>
          <el-checkbox label="remove">删除</el-checkbox>
          <el-checkbox label="list_options">下拉选项</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="前端接口需要登录" v-if="columns.length">
        <el-switch v-model="api_need_login"></el-switch>
        <span  class="alert-danger">是否必须登录后才能访问</span>
      </el-form-item>
      <el-form-item label="前端接口关联用户" v-if="columns.length">
        <el-switch v-model="api_user_id"></el-switch>
        <span  class="alert-danger">设置后用户只能查询、操作自己的数据</span>
      </el-form-item>
      <el-form-item label="是否创建权限" v-if="columns.length">
        <el-switch v-model="isCreatePermission"></el-switch>
        <span  class="alert-danger">不设置就是纯接口模式，或者自己手动创建！</span>
      </el-form-item>

      <el-form-item label="菜单名称" v-if="columns.length && isCreatePermission">
        <el-input v-model="menu_name" placeholder="请输入菜单名称" style="width: 250px"></el-input>
        <br>
        <span class="alert-danger">
          相关权限将设置在该菜单下，后期可以自行修改位置。多次操作同一个表以第一次为准！
        </span>
      </el-form-item>
      <!-- 字段配置区域 -->
      <template v-if="columns.length">
        <div class="columns-config">
          <h3>字段配置</h3>
          <el-table :data="columns" border>
            <el-table-column prop="Field" label="字段名" width="180"></el-table-column>
            <el-table-column prop="Comment" label="字段注释" width="200"></el-table-column>

            <!-- 搜索配置 -->
            <el-table-column label="搜索配置" width="250">
              <template #default="{ row }">
                <el-checkbox v-model="row.isSearchable">
                  可搜索
                </el-checkbox>
                <el-input
                  v-if="row.isSearchable"
                  v-model="row.searchDisplayName"
                  size="small"
                  placeholder="显示名称"
                ></el-input>
                <el-input-number
                  v-if="row.isSearchable"
                  v-model="row.searchOrder"
                  :min="1"
                  size="small"
                  placeholder="排序"
                ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="列表字段" width="200">
              <template #default="{ row }">
                <el-checkbox v-model="row.isShowList">
                  显示在列表
                </el-checkbox>
                <el-input
                  v-if="row.isShowList"
                  v-model="row.ShowListDisplayName"
                  size="small"
                  placeholder="显示名称"
                ></el-input>
                <el-input-number
                  v-if="row.isShowList"
                  v-model="row.showListOrder"
                  :min="1"
                  size="small"
                  placeholder="排序"
                ></el-input-number>
              </template>
            </el-table-column>

            <!-- 表单配置 -->
            <el-table-column label="表单配置" width="200">
              <template #default="{ row }">
                <el-checkbox v-model="row.isEditable">可编辑</el-checkbox>
                <el-checkbox v-model="row.isRequired">必填</el-checkbox>
              </template>
            </el-table-column>

            <!-- 字段类型 -->
            <el-table-column label="字段类型" width="200">
              <template #default="{ row }">
                <el-select v-model="row.componentType">
                  <el-option label="输入框" value="input"></el-option>
                  <el-option label="多行文本" value="textarea"></el-option>
                  <el-option label="日期选择器" value="date"></el-option>
                  <el-option label="日期时间选择器" value="datetime"></el-option>
                  <el-option label="时间选择器" value="time"></el-option>
                  <el-option label="日期范围" value="daterange"></el-option>
                  <el-option label="选择器" value="select"></el-option>
                  <el-option label="数字输入框" value="number_input"></el-option>
                  <el-option label="计步器" value="number"></el-option>
                  <el-option label="开关" value="switch"></el-option>
                  <el-option label="上传图片(单图)" value="upload-image"></el-option>
                  <el-option label="上传多图" value="upload-images"></el-option>
                  <el-option label="上传文件(单文件)" value="upload-file"></el-option>
                  <el-option label="上传多文件" value="upload-files"></el-option>
                </el-select>

              </template>
            </el-table-column>

            <!-- 选项配置 -->
            <el-table-column label="选项配置" width="200">
              <template #default="{ row }">
                <el-button
                  v-if="row.componentType === 'select'"
                  size="small"
                  @click="handleConfigOptions(row)"
                >
                  配置选项
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 生成按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleGenerate" :loading="isGenerating">生成CRUD代码</el-button>
        </el-form-item>
      </template>
    </el-form>

    <!-- 选项配置对话框 -->
    <el-dialog
      :visible.sync="optionsDialog.visible"
      v-model="optionsDialog.visible"
      title="配置选项"
      width="500px"
      modal
      lock-scroll
      :close-on-click-modal="false"
    >
      <el-form v-if="optionsDialog.currentColumn">
        <el-form-item label="选项来源">
          <el-radio-group v-model="optionsDialog.currentColumn.optionsSource">
            <el-radio label="static">静态选项</el-radio>
            <el-radio label="api">接口获取</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 静态选项配置 -->
        <template v-if="optionsDialog.currentColumn.optionsSource === 'static'">
          <div
            v-for="(option, index) in optionsDialog.currentColumn.options"
            :key="index"
            class="option-item"
          >
            <el-input v-model="option.label" placeholder="选项文本"></el-input>
            <el-input v-model="option.value" placeholder="选项值"></el-input>
            <el-button @click="removeOption(index)" type="danger" icon="el-icon-delete" size="mini"></el-button>
          </div>
          <el-button @click="addOption" type="primary">添加选项</el-button>
        </template>

        <!-- API选项配置 -->
        <template v-else>
          <el-form-item label="接口地址">
            <el-input v-model="optionsDialog.currentColumn.apiUrl"></el-input>
          </el-form-item>
          <el-form-item label="标签字段">
            <el-input v-model="optionsDialog.currentColumn.labelField"></el-input>
          </el-form-item>
          <el-form-item label="值字段">
            <el-input v-model="optionsDialog.currentColumn.valueField"></el-input>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="optionsDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveOptions">确定</el-button>
      </template>
    </el-dialog>
  </div>
</div>
{/block}

{block name="script"}
<script>
  var api_base = '/curd';
  new Vue({
    el: '#app',
    data() {
      return {
         config: {
          tableName: ''
        },
        isCreatePermission: true,
        api_need_login: true,
        api_user_id: true,
        menu_name: '',
        apis: ['list', 'detail'],
        admin_apis: ['save_data','edit_data','list'],
        columns: [],
        optionsDialog: {
          visible: false,
          currentColumn: null
        },
        isLoading: false,
        isGenerating: false
      };
    },
    methods: {
       handleCreateTable(){
        location.href="{:url('create_table')}"
      },
      // 表名变更时查询表结构
      async handleTableNameChange(val) {
        if (!val) {
          this.columns = []
          return
        }
        // 验证表名格式
        if (!/^[a-zA-Z0-9_]+$/.test(val)) {
          this.$message.error('表名只能包含字母、数字和下划线')
          return
        }
        this.isLoading = true
        try {
          const res = await get(api_base+'/table_info',{ table_name: val,for_query:true })
          if (res.code !== 0) {
            this.$message.error(res.msg)
            return
          }
          // 为每个字段添加配置属性
          this.columns = res.data.map(col => ({
            ...col,
            isSearchable: false,
            isShowList: true,
            showListOrder: 1,
            searchOrder: 1,
            ShowListDisplayName: col.Comment || col.Field,
            searchDisplayName: col.Comment || '', // 默认值为字段名
            isEditable: false,
            isRequired: false,
            componentType: 'input',
            optionsSource: 'static',
            options: [{ label: '默认选项', value: 'default' }], // 默认选项
            apiUrl: '',
            labelField: '',
            valueField: ''
          }))
        } catch (error) {
          console.error('获取表结构失败:', error)
          this.$message.error('获取表结构失败，请检查网络或联系管理员')
        } finally {
          this.isLoading = false
        }
      },

      // 打开选项配置对话框
      handleConfigOptions(row) {
        console.log('配置选项', row)
        if (!row.options) {
          row.options = [{ label: '默认选项', value: 'default' }]
        }
        if (!row.optionsSource) {
          row.optionsSource = 'static'
        }

        this.optionsDialog.currentColumn = JSON.parse(JSON.stringify(row))
        this.optionsDialog.visible = true
      },

      // 添加选项
      addOption() {
        if (this.optionsDialog.currentColumn) {
          this.optionsDialog.currentColumn.options.push({
            label: '新选项',
            value: ''
          })
        }
      },

      // 删除选项
      removeOption(index) {
        if (this.optionsDialog.currentColumn) {
          this.optionsDialog.currentColumn.options.splice(index, 1)
        }
      },

      // 修改保存选项方法
      saveOptions() {
        if (this.optionsDialog.currentColumn.optionsSource === 'api') {
          if (!this.optionsDialog.currentColumn.apiUrl || !this.optionsDialog.currentColumn.labelField || !this.optionsDialog.currentColumn.valueField) {
            this.$message.error('请填写完整的接口配置信息')
            return
          }
        }
        // 找到原始行数据
        const originalRow = this.columns.find(
          col => col.Field === this.optionsDialog.currentColumn.Field
        )

        if (originalRow) {
          // 更新原始行的选项相关数据
          originalRow.optionsSource = this.optionsDialog.currentColumn.optionsSource
          originalRow.options = [...this.optionsDialog.currentColumn.options]
          originalRow.apiUrl = this.optionsDialog.currentColumn.apiUrl
          originalRow.labelField = this.optionsDialog.currentColumn.labelField
          originalRow.valueField = this.optionsDialog.currentColumn.valueField
        }

        this.optionsDialog.visible = false
        this.optionsDialog.currentColumn = null
      },

      // 生成CRUD代码
      async handleGenerate() {
        if (!this.config.tableName) {
          this.$message.error('请输入表名')
          return
        }
        if (this.columns.length === 0) {
          this.$message.error('请先查询表结构')
          return
        }
        this.isGenerating = true
        try {
          const config = {
            tableName: this.config.tableName,
            admin_apis: this.admin_apis,
            apis: this.apis,
            menu_name: this.menu_name,
            isCreatePermission: this.isCreatePermission,
            api_need_login: this.api_need_login,
            api_user_id: this.api_user_id,
            columns: this.columns
          }
          console.log(config)
          await post(api_base+'/save',config)
            .then(res => {
              console.log('create',res)
              if (res.code === 0) {
                this.$message.success('生成代码成功')
              }else if(res.code === -100){
                //需要二次确认
                this.$confirm('已存在同名文件，是否覆盖？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    // 确定覆盖
                   config.overwrite = true
                    post(api_base+'/save',config)
                    .then(res => {
                      console.log('create',res)
                      if (res.code === 0) {
                        this.$message.success('生成代码成功')
                      }else {
                        this.$message.error(res.msg)
                      }
                    })
                  }).catch(() => {
                    // 取消覆盖
                    this.$message.info('已取消覆盖')
                })
              } else {
                this.$message.error(res.msg)
              }
            })
          // 这里可以添加下载生成的代码或其他后续处理
        } catch (error) {
          console.error('生成代码失败:', error)
          this.$message.error('生成代码失败，请检查网络或联系管理员')
        } finally {
          this.isGenerating = false
        }
      }
    },
    mounted() {
    }
  });
</script>
{/block}
